package cn.hanna.springcloudalibaba.controller;

import cn.hanna.springcloud.entities.CommonResult;
import cn.hanna.springcloudalibaba.handler.BlockExceptionHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author smileha
 * @create 2021-10-22 0:50
 * @description
 */
@RestController
public class RateLimitController {

    // 跟据资源名进行限流
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "rateLimitByResource")
    public CommonResult rateLimitByResource(){
        return new CommonResult(200,"此时流量未达到上限",null);
    }

    public CommonResult handleByResource(BlockException blockException){
        return new CommonResult(444,"根据资源名进行限流：此时流量达到上限，请稍后再试",null);
    }

    //跟据URL进行限流
    @GetMapping("/byURL")
    @SentinelResource(value = "byURL")
    public CommonResult rateLimitByURL(){
        return new CommonResult(200,"此时流量未达到上限",null);
    }

    // 测试自定义的BlockException类，抽取公共的处理BlockException异常的方法
    @GetMapping("/test/blockException/handler")
    @SentinelResource(value = "blockExceptionHandler",
                      blockHandlerClass = BlockExceptionHandler.class,
                      blockHandler = "handleByResource1")
    public CommonResult testBlockExceptionHandler(){
        return new CommonResult(200,"此时流量未达到上限",null);
    }
}
